import os
import sys
from string import Template
from pkg_tools import cmd, logger, cmd_with_result, write_file, make_dir_p, join_path, url_retrieve, create_tar_gz, \
    remove_file_or_dir, release_package_remove_src
from conf_common import project_name, build_number, custom_install_cmd, custom_private_cmd, module_name
from conf_frontend import front_end_folders, project_nginx_conf, ssl_server_key, ssl_server_perm, node_v

base_path = f'{project_name}-{module_name}-install'
pwd = os.getcwd()


def build_all_front_end():
    if front_end_folders is None or len(front_end_folders) == 0:
        return
    front_end_folder_arr = front_end_folders.split(',')
    for front_end_folder in front_end_folder_arr:
        source_target = front_end_folder.split(':')
        tc_source = source_target[0]
        build_target = source_target[1]
        nginx_target = source_target[2]
        current_path = join_path(pwd, tc_source)
        logger.info('===> node_v,%s' % node_v)
        if '14' == node_v:
            cmd("export NODE=/usr/local/node14/bin && export PATH=$NODE:$PATH && npm install --unsafe-perm=true --allow-root --prefix %s" % current_path)
            cmd("export NODE=/usr/local/node14/bin && export PATH=$NODE:$PATH && npm run build --prefix %s" % current_path)
        else:
            cmd("npm install --unsafe-perm=true --allow-root --prefix %s" % current_path)
            cmd("npm run build --prefix %s" % current_path)
        mv_2_nginx_target_path = join_path(pwd, base_path, 'pkg', nginx_target)
        make_dir_p(mv_2_nginx_target_path)
        cmd("cp -rf {}/* {}".format(join_path(current_path, build_target), mv_2_nginx_target_path))
        cmd_with_result("ls -la %s" % mv_2_nginx_target_path)


def create_xwguard_env_file():
    create_xwguard_install_conf()
    create_xwguard_private_conf()
    create_xwguard_start_sh()
    create_xwguard_bin()
    create_xwguard_xagent()


def create_xwguard_install_conf():
    conf = Template('''
[install]

cd $${workdir}
cp -rf conf html log sbin ${module_name}.conf version.txt start.sh pkg $${installdir}
# 自定义脚本
${custom_install_cmd}

# 没有这个目录，启动报错
mkdir -p /usr/local/nginx/logs

[uninstall]
#用于配置卸载时模块的特殊处理
''')
    conf_content = conf.substitute({'module_name': module_name, 'custom_install_cmd': custom_install_cmd})
    write_file(join_path(pwd, base_path, 'install.conf'), conf_content)


def create_xwguard_private_conf():
    write_file(join_path(pwd, base_path, 'private.conf'), custom_private_cmd)


def create_xwguard_start_sh():
    conf = Template("""#!/bin/bash

workdir=$$(cd $$(dirname $$0) && pwd)
echo $$workdir

proc=$$(ps -ef|grep "${module_name}"|grep -v grep)

if [ "x$$proc" = "x" ];then
    echo "start ${module_name}"
    cd $$workdir
    ./sbin/nginx -c /usr/local/${module_name}/${module_name}.conf
else
    echo "${module_name} is running"
    exit 1
fi

exit 0""")
    conf_content = conf.substitute({'module_name': module_name})
    write_file(join_path(pwd, base_path, 'start.sh'), conf_content)
    pass


def create_xwguard_bin():
    conf = Template('''rundir = /usr/local/${module_name}
runcmd = ./start.sh
match = ${module_name}.conf
profiles =''')
    conf_content = conf.substitute({'module_name': module_name})
    write_file(join_path(pwd, base_path, f'{module_name}.guard'), conf_content)


def create_xwguard_xagent():
    write_file(join_path(pwd, base_path, f'{module_name}.xagent'), '')


def create_nginx_conf():
    conf = Template('''#user  nobody;
worker_processes  2;
worker_shutdown_timeout 3;

error_log  /usr/local/${module_name}/log/main_error.log info;

pid        /usr/local/${module_name}/log/nginx.pid;

events
{
    worker_connections  1024;
}

http
{
    include            conf/mime.types;
    default_type       application/octet-stream;
    log_format         main  '$$remote_addr - $$remote_user [$$time_local] "$$request" $$status $$body_bytes_sent "$$http_referer" "$$http_user_agent" "$$http_x_forwarded_for"';
    access_log         /usr/local/${module_name}/log/access.log;
    error_log          /usr/local/${module_name}/log/error.log error;
    sendfile           on;
    keepalive_timeout  300;
    client_max_body_size 4096m; # 限制客户端请求的最大消息体大小为 8 MB
    #tcp_nopush         on;

    ##nginx gzip compress
    gzip on;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1k;
    gzip_vary on;
    gzip_proxied any;
    gzip_disable "MSIE [1-6].";

    #server
    include             conf/*.conf;

    server_tokens               off;
}
    ''')
    content_conf = conf.substitute({'module_name': module_name})
    write_file(join_path(pwd, base_path, f'{module_name}.conf'), content_conf)


def create_project_nginx_conf():
    make_dir_p(join_path(pwd, base_path, 'conf'))
    write_file(join_path(pwd, base_path, 'conf', 'mime.types'), """
types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

    text/mathml                                      mml;
    text/plain                                       txt;
    text/vnd.sun.j2me.app-descriptor                 jad;
    text/vnd.wap.wml                                 wml;
    text/x-component                                 htc;

    image/png                                        png;
    image/svg+xml                                    svg svgz;
    image/tiff                                       tif tiff;
    image/vnd.wap.wbmp                               wbmp;
    image/webp                                       webp;
    image/x-icon                                     ico;
    image/x-jng                                      jng;
    image/x-ms-bmp                                   bmp;

    font/woff                                        woff;
    font/woff2                                       woff2;

    application/java-archive                         jar war ear;
    application/json                                 json;
    application/mac-binhex40                         hqx;
    application/msword                               doc;
    application/pdf                                  pdf;
    application/postscript                           ps eps ai;
    application/rtf                                  rtf;
    application/vnd.apple.mpegurl                    m3u8;
    application/vnd.google-earth.kml+xml             kml;
    application/vnd.google-earth.kmz                 kmz;
    application/vnd.ms-excel                         xls;
    application/vnd.ms-fontobject                    eot;
    application/vnd.ms-powerpoint                    ppt;
    application/vnd.oasis.opendocument.graphics      odg;
    application/vnd.oasis.opendocument.presentation  odp;
    application/vnd.oasis.opendocument.spreadsheet   ods;
    application/vnd.oasis.opendocument.text          odt;
    application/vnd.openxmlformats-officedocument.presentationml.presentation
                                                     pptx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                                                     xlsx;
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
                                                     docx;
    application/vnd.wap.wmlc                         wmlc;
    application/x-7z-compressed                      7z;
    application/x-cocoa                              cco;
    application/x-java-archive-diff                  jardiff;
    application/x-java-jnlp-file                     jnlp;
    application/x-makeself                           run;
    application/x-perl                               pl pm;
    application/x-pilot                              prc pdb;
    application/x-rar-compressed                     rar;
    application/x-redhat-package-manager             rpm;
    application/x-sea                                sea;
    application/x-shockwave-flash                    swf;
    application/x-stuffit                            sit;
    application/x-tcl                                tcl tk;
    application/x-x509-ca-cert                       der pem crt;
    application/x-xpinstall                          xpi;
    application/xhtml+xml                            xhtml;
    application/xspf+xml                             xspf;
    application/zip                                  zip;

    application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;
}""")
    write_file(join_path(pwd, base_path, 'conf', 'project_nginx.conf'), project_nginx_conf)


def create_nginx_html():
    make_dir_p(join_path(pwd, base_path, 'html'))
    write_file(join_path(pwd, base_path, 'html', '50x.html'), """<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>An error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the error log for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
""")
    write_file(join_path(pwd, base_path, 'html', 'index.html'), """<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
""")


def create_log_dir():
    make_dir_p(join_path(pwd, base_path, 'log'))
    write_file(join_path(pwd, base_path, 'log', '.empty-keep'), '')


def create_nginx_sbin():
    make_dir_p(join_path(pwd, base_path, 'sbin'))
    url_retrieve('http://samba.xw/xianwei/thirdparty/nginx', join_path(pwd, base_path, 'sbin', 'nginx'))


def create_nginx_ssl():
    make_dir_p(join_path(pwd, base_path, 'ssl'))
    write_file(join_path(pwd, base_path, 'ssl', 'server.key'), ssl_server_key)
    write_file(join_path(pwd, base_path, 'ssl', 'server.perm'), ssl_server_perm)


def release_package():
    write_file(join_path(base_path, 'version.txt'), build_number)
    release_package_remove_src(base_path, f'{base_path}-{build_number}.tar.gz')


if __name__ == '__main__':
    try:
        make_dir_p(base_path)
        build_all_front_end()
        create_xwguard_env_file()
        create_nginx_conf()
        create_project_nginx_conf()
        create_nginx_html()
        create_log_dir()
        create_nginx_sbin()
        create_nginx_ssl()
        release_package()
    except Exception as err:
        logger.error('main exception:' + str(err))
        sys.stderr.write('main exception:' + str(err))
        sys.exit(1)
